import json
import socket
import struct
import sys
import threading
import time

from utils.decorator import async_func

a = b'U\x07\x00\x00\x1d\x02\x00\x01\x00\x00\x00\x00M6F-D070-20220523-001\x00,\xf4'
upload_data = b'U\x02\x04\x00HC\xee\xff\x96B\nhm\xc3?^\x89\xbf\x03Z\xad\xc1\x10\xeb\xda\xc0\xb3\x9d3C\xef\x9f\xafD\x01\x02\xc1A*\xb0\x7fC\xee\xff\x96B\nhm\xc3?^\x89\xbf\x03Z\xad\xc1\x10\xeb\xda\xc0\xb3\x9d3C\xef\x9f\xafD\x01\x02\xc1A*\xb0\x7fQ\x97'
HOST, PORT = "localhost", 6802
lock = threading.Lock()


class TCPConn:

    def __init__(self):
        self.connect()
        self.send_count = 0
        self.inited = False

    def connect(self):
        while True:
            try:
                with lock:
                    self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    self.conn.connect((HOST, PORT))
                    break
            except Exception as e:
                print(f'reconnect error, msg: {e.args}')
                time.sleep(0.2)

    # @async_func
    def read(self):
        while True:
            try:
                received = self.conn.recv(1024)
                print("Received: {}".format(received))
                time.sleep(0.2)
            except socket.error as e:
                self.inited = False
                print(e.args)

    # @async_func
    def write(self):
        while True:
            try:
                if not self.inited:
                    self.conn.sendall(a)
                    self.inited = True
                else:
                    self.upload()
            except socket.error as e:
                self.inited = False
                print('write error: ', e.args)
                self.connect()

    def upload(self):
        # print(f'send data: {upload_data}')
        self.conn.sendall(upload_data)

    def _third(self, conn):
        received = conn.recv(1024)
        print("Received: {}".format(received))
        time.sleep(0.2)


if __name__ == '__main__':

    source = 'M6F-D070-20220523-001'

    ins = TCPConn()

    t1 = threading.Thread(target=ins.write)
    t1.start()

    t2 = threading.Thread(target=ins.read)
    t2.start()



